<template>

	<view class="scrollConter">
		<view class="bar">
			<statusTab @checkTab="checkTabClick" ref="statusTabRef" :list="list1" />
		</view>
		<view class="conterRow" v-if="listData.length == 0 && !isLoading">
			<view class="nullData">
				<image src="https://img.zhizhuangtong.com/project_media/img/xcx/null.png" mode=""></image>
				<text>暂无数据</text>
			</view>
		</view>

		<view class="conterRow" v-else>
			<view class="cards" :class='item.child?"a":""' v-for="(item,index) in listData" :key="index">
				<template v-if="!item.child">
					<view @click.prevent="onDetails(item.id)">
						<!-- 头部 -->
						<view class="flex_row_btw_center" v-if="item.corp&&item.corp.company_name">
							<view class="label">
								<image src="../../../../static/ucenter/dianpu@2x.png" mode="" class="img"></image>
								<text>{{item.corp.company_name}}</text>
								<image src="https://img.zhizhuangtong.com/project_media/img/xcx/rightTag.png"
									class="imgs" />
							</view>
							<view class="statusText" v-if="item.status==2||item.status==3||item.status==4">
								{{item.status_text}}
							</view>
							<view class="statusText statusText1" v-if="item.status==1||item.status==5">
								{{item.status_text}}
							</view>
						</view>
						<view class="flex_row_btw_center" v-else>
							<view class="label">
								<image src="/static/image/logo.png" mode="" class="imgBox"></image>
							</view>
							<view class="statusText" v-if="item.status==2||item.status==3||item.status==4">
								{{item.status_text}}
							</view>
							<view class="statusText statusText1" v-if="item.status==1||item.status==5">
								{{item.status_text}}
							</view>
						</view>
						<!-- 商品信息区域 -->
						<view class="main">
							<view class="flex_row_btw_start" v-for="(ite,goodIndex) in item.goods" :key='goodIndex'
								v-if="item.goods.length==1">
								<view class="flex_row_start_top">
									<image :src="ite.img" mode="" class="img"></image>
									<view class="flex-column-between-start">
										<view class="title">
											{{ite.goods_title}}{{ite.sku_name}}
										</view>
										<view class="intro">
											尺寸{{ite.size}}
										</view>
									</view>
								</view>
								<view class="flex-column-between-end right">
									<view class="flex_row_btw_end">
										<view class="unit">¥</view>
										<view class="price">{{item.order_money}}</view>
									</view>
									<view class="intros">
										共{{ite.num}}件
									</view>
								</view>
							</view>
							<view class="flex_row_btw_center" v-else>
								<view class="flex_row_start_top imgShowBox">
									<!-- <up-scroll-list :indicator='false' style="width: 300rpx;padding-bottom: 0 !important;"> -->
									<view v-for="(ite,goodIndex) in item.goods" :key='goodIndex'
										style="width: 300rpx;padding-bottom: 0 !important;">
										<image :src="ite.img" mode="" class="img" style="margin-right: 10rpx;">
										</image>
									</view>
									<!-- </up-scroll-list> -->
								</view>

								<view class="flex-column-between-end right">
									<view class="flex_row_btw_end">
										<view class="unit">¥</view>
										<view class="price">{{item.need_pay}}</view>
									</view>
									<view class="intros">
										共{{item.num}}件
									</view>
								</view>
							</view>
						</view>
						<view class="tips type1" v-if="item.status==2">
							<template v-if="isTimeValid(item.auto_cancel)">
								<up-icon name="clock" color="#999" size="15"></up-icon>
								<text class="name">等待支付</text>
								<text class="tishi">剩余</text>
								<text class="value">{{ item.remainingCancelTime }}</text>
							</template>
							<template v-else>
								<up-icon name="clock" color="#999" size="15"></up-icon>
								<text class="name">已超时</text>
							</template>
						</view>
						<view class="btn" v-if="item.status==2||item.status==3||item.status==4">
							<view @click.prevent="closeOrder(item.id,'close')" v-if="item.status==2||item.status==3">
								取消订单
							</view>
							<view @click.prevent="submitOrderClick(item.id)" class="type2"
								v-if="item.status==2&&isTimeValid(item.auto_cancel)">去支付</view>
							<view @click.prevent="closeOrder(item.id,'collect')" class="type2" v-if="item.status==4">
								确认收货
							</view>
						</view>
					</view>
				</template>
				<template v-else>
					<template v-for="(its,index) in item.child" :key="index">
						<view @click.prevent="onDetails(its.id)" class="itemBox">
							<!-- 头部 -->
							<view class="flex_row_btw_center" v-if="its.corp&&its.corp.company_name">
								<view class="label">
									<image src="../../../../static/ucenter/dianpu@2x.png" mode="" class="img"></image>
									<text>{{its.corp.company_name}}</text>
									<image src="https://img.zhizhuangtong.com/project_media/img/xcx/rightTag.png"
										class="imgs" />
								</view>
								<view class="statusText" v-if="its.status==2||its.status==3||its.status==4">
									{{its.status_text}}
								</view>
								<view class="statusText statusText1" v-if="its.status==1||its.status==5">
									{{its.status_text}}
								</view>
							</view>
							<view class="flex_row_btw_center" v-else>
								<view class="label">
									<image src="/static/image/logo.png" mode="" class="imgBox"></image>
								</view>
								<view class="statusText" v-if="its.status==2||its.status==3||its.status==4">
									{{its.status_text}}
								</view>
								<view class="statusText statusText1" v-if="its.status==1||its.status==5">
									{{its.status_text}}
								</view>
							</view>
							<!-- 商品信息区域 -->
							<view class="main">
								<view class="flex_row_btw_start" v-for="(ite,goodIndex) in its.goods" :key='goodIndex'
									v-if="its.goods.length==1">
									<view class="flex_row_start_top">
										<image :src="ite.img" mode="" class="img"></image>
										<view class="flex-column-between-start">
											<view class="title">
												{{ite.goods_title}}{{ite.sku_name}}
											</view>
											<view class="intro">
												尺寸{{ite.size}}
											</view>
										</view>
									</view>
									<view class="flex-column-between-end right">
										<view class="flex_row_btw_end">
											<view class="unit">¥</view>
											<view class="price">{{its.order_money}}</view>
										</view>
										<view class="intros">
											共{{ite.num}}件
										</view>
									</view>
								</view>
								<view class="flex_row_btw_center" v-else>
									<view class="flex_row_start_top imgShowBox">
										<!-- <up-scroll-list :indicator='false' style="width: 300rpx;padding-bottom: 0 !important;"> -->
										<view v-for="(ite,goodIndex) in its.goods" :key='goodIndex'
											style="width: 300rpx;padding-bottom: 0 !important;">
											<image :src="ite.img" mode="" class="img" style="margin-right: 10rpx;">
											</image>
										</view>
										<!-- </up-scroll-list> -->
									</view>

									<view class="flex-column-between-end right">
										<view class="flex_row_btw_end">
											<view class="unit">¥</view>
											<view class="price">{{its.need_pay}}</view>
										</view>
										<view class="intros">
											共{{its.num}}件
										</view>
									</view>
								</view>
							</view>
							<view class="tips type1" v-if="its.status==2">
								<template v-if="isTimeValid(its.auto_cancel)">
									<up-icon name="clock" color="#999" size="15"></up-icon>
									<text class="name">等待支付</text>
									<text class="tishi">剩余</text>
									<text class="value">{{ its.remainingCancelTime }}</text>
								</template>
								<template v-else>
									<up-icon name="clock" color="#999" size="15"></up-icon>
									<text class="name">已超时</text>
								</template>
							</view>
							<view class="btn" v-if="its.status==2||its.status==3||its.status==4">
								<view @click.prevent="closeOrder(its.id,'close')" v-if="its.status==2||its.status==3">
									取消订单</view>
								<view @click.prevent="submitOrderClick(its.id)" class="type2"
									v-if="its.status==2&&isTimeValid(its.auto_cancel)">去支付</view>
								<view @click.prevent="closeOrder(its.id,'collect')" class="type2" v-if="its.status==4">
									确认收货</view>
							</view>
						</view>
					</template>
				</template>
			</view>

		</view>
		<view v-if="isLoading" class="load-more-box">
			<text>加载中...</text>
		</view>

		<view v-if="listData.length !== 0 && !isLoading && !hasMoreData" class="load-more-box">
			<text>已经到底了</text>
		</view>

		<up-popup :show="showClose" :round="10" mode="center" @close="showClose = false" @open="showClose = true">
			<closeItem @closeModel="showClose = false" @saveModel='orderClose' ref="closeOrderRef" />
		</up-popup>
		<!-- showClose -->
	</view>

</template>

<script setup>
	import {
		list
	} from '@/api/mineOrder.js';
	import closeItem from '@/components/closeItem.vue'
	import {
		ref,
		onMounted,
		defineExpose,
		watch,
		reactive,
		onUnmounted
	} from 'vue';
	import {
		onLoad,
		onReady,
		onShow,
		onHide,
		onShareAppMessage,
		onShareTimeline,
		onReachBottom,
		onPullDownRefresh
	} from '@dcloudio/uni-app'
	import statusTab from '@/components/statusTab/index.vue'

	const active = ref('')

	const statusTabRef = ref(null)

	const params = ref({
		status: '',
		page: 1,
		page_size: 10
	})
	const listData = ref([]) //列表数据

	// tabs数据
	const list1 = ref([{
			name: '全部',
		},
		{
			name: '待付款',
		},
		{
			name: '待收货',
		},
		{
			name: '已完成',
		},
		{
			name: '已失效',
		}
	])
	const show = ref(false);
	const checkStatus = ref(0)
	onLoad((option) => {
		listData.value = []
		params.value.status = '0'
		params.value.page = 1
		if (option.status) {
			params.value.status = option.status;
			if (params.value.status == 0) {
				checkStatus.value = 0
			} else if (params.value.status == 1) {
				checkStatus.value = 4
			} else if (params.value.status == 2) {
				checkStatus.value = 1

			} else if (params.value.status == 5) {
				checkStatus.value = 3
			} else {
				checkStatus.value = 2
			}
		}
		params.value.page = 1;
		listData.value = []
		queryDemandList()

	})
	onReady(() => {
		if (statusTabRef.value) {
			statusTabRef.value.active = checkStatus.value
		}
	})
	onShow(() => {
		// 标记是否已经执行过外部的请求
		let hasTriggered = false;
		uni.$on('refreshIfNeeded1', function(dat) {
			if (dat && !hasTriggered) {
				console.log(dat)
				params.value.page = 1;
				listData.value = []
				queryDemandList()
			}
			uni.$off('refreshIfNeeded1')
		})
		startInterval()
		if (!hasTriggered) {
			hasTriggered = false; // 外部操作已触发
		}
	})

	// onMounted(() => {

	// });

	onReachBottom(() => {
		queryDemandList()
	});
	//tab点击
	const checkTabClick = (val) => {
		checkStatus.value = val
		if (val == 0) {
			params.value.status = 0
		} else if (val == 1) {
			params.value.status = 2
		} else if (val == 2) {
			params.value.status = 4
		} else if (val == 3) {
			params.value.status = 5
		} else if (val == 4) {
			params.value.status = 1
		}
		params.value.page = 1
		listData.value = []
		queryDemandList()
	}

	// 数据列表、加载状态和分页参数
	const hasMoreData = ref(true); // 初始化为true，表示还有更多数据
	const isLoading = ref(false); // 加载状态
	const changeTreeData = (nodes) => {
		nodes.forEach((item) => {
			if (item.goods) {
				item.goods = changeTreeData(item.goods);
				item.num = 0;
				item.goods.forEach((elm) => {
					item.num += elm.num;
				})

			}
		})
		return nodes;
	}
	// 需求列表
	const queryDemandList = async () => {

		isLoading.value = true; // 设置加载中
		try {
			const res = await list(params.value);
			if (res.code === 1) {
				changeTreeData(res.data.list)
				if (params.value.page === 1) {
					// listData.value = res.data.list.map(item => ({
					// 	...item,
					// 	isExpired: item.order ? checkIfExpired(item.order.auto_cancel) : false
					// }));
					listData.value = res.data.list
				} else {
					// 如果不是第一页，添加到现有 listData 中
					// listData.value.push(...res.data.list.map(item => ({
					// 	...item,
					// 	isExpired: item.order ? checkIfExpired(item.order.auto_cancel) : false
					// })));
					listData.value.push(...res.data.list);
				}

				// 判断是否还有更多数据
				if (res.data.list.length < params.value.page_size) {
					hasMoreData.value = false; // 没有更多数据
				} else {
					hasMoreData.value = true; // 还有更多数据
				}
				params.value.page += 1; // 页码递增
			}
			setTimeout(() => {
				isLoading.value = false;
			}, 500);
		} catch (error) {
			console.error('请求数据失败:', error);
		} finally {
			isLoading.value = false; // 加载完成

		}
	}

	const formatRemainingTime = (endTime) => {
		const now = new Date()
		const end = new Date(endTime)
		const diff = end - now
		if (diff <= 0) return '00:00:00'
		const hours = String(Math.floor(diff / (1000 * 60 * 60))).padStart(2, '0')
		const minutes = String(
			Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60)),
		).padStart(2, '0')
		const seconds = String(Math.floor((diff % (1000 * 60)) / 1000)).padStart(
			2,
			'0',
		)
		return `${hours}时${minutes}分${seconds}秒`
	}

	const updateTimes = () => {
		listData.value.forEach((item) => {
			item.remainingCancelTime = formatRemainingTime(item.auto_cancel)
		})
	}
	const state = reactive({
		intervals: [],
	})
	const startInterval = () => {
		updateTimes()
		state.intervals.push(
			setInterval(() => {
				updateTimes()
			}, 1000),
		)
	}


	onUnmounted(() => {
		state.intervals.forEach(clearInterval)
	})
	onHide(() => {
		state.intervals.forEach(clearInterval)
	})
	const isTimeValid = (endTime) => {
		const now = new Date()
		const end = new Date(endTime)
		return end > now
	}

	// 判断是否超过截止时间
	const checkIfExpired = (autoCancelTime) => {
		const currentTime = new Date();
		const cancelTime = new Date(autoCancelTime);
		// 转换为 UTC 时间戳来进行比较
		const currentTimestamp = currentTime.getTime(); // 当前时间的时间戳（毫秒）
		const cancelTimestamp = cancelTime.getTime(); // 截止时间的时间戳（毫秒）
		console.log('autoCancelTime', autoCancelTime);
		console.log('当前时间', currentTime);
		console.log('截止时间', cancelTime);
		return currentTimestamp > cancelTimestamp;
	};



	const showClose = ref(false)
	const closeOrderRef = ref()
	// 取消订单
	const closeOrder = async (id, type) => {
		showClose.value = true
		closeOrderRef.value.type = type
		closeOrderRef.value.orderId = id
	}
	const orderClose = () => {
		showClose.value = false
		params.value.page = 1;
		queryDemandList()
	}


	// 订单详情
	const onDetails = (id) => {
		uni.navigateTo({
			url: '/pages/mineB/mineOrder/mineOrderDetails/index?id=' + id
		});
	}


	// 提交订单 去收银台
	const submitOrderClick = async (id) => {

		setTimeout(() => {
			const navigateUrl =
				`/pages/order/cashierCounter/index?order_id=${id}`;
			uni.navigateTo({
				url: navigateUrl
			});
		}, 500);
	};
</script>

<style lang="less" scoped>
	.a {
		background: none !important;
		padding: 0 !important;
	}

	.itemBox {
		margin-bottom: 20rpx;
		background: #fff;
		padding: 30rpx 20rpx 30rpx;
		border-radius: 16rpx;
	}

	.itemBox:nth-last-of-type(1) {
		margin-bottom: 0;
	}

	.tabs {
		width: 100%;
		height: 100%;
		background-color: #fff;
		display: flex;
		justify-content: space-around;
	}

	.scrollConter {
		width: 100%;
		min-height: 100vh;
		box-sizing: border-box;
		background-color: #f2f2f2;
		display: flex;
		align-content: flex-start;
		flex-wrap: wrap;

		.bar {
			height: 80rpx;
			width: 100%;
		}

		.conterRow {
			width: 100%;
			height: calc(100% - 80rpx);
			padding: 20rpx 20rpx 0;
			box-sizing: border-box;

			.cards {
				width: 100%;
				background: #FFFFFF;
				border-radius: 18rpx;
				padding: 30rpx 20rpx 30rpx;
				margin-bottom: 20rpx;
				box-sizing: border-box;

				&:last-child {
					margin-bottom: 0;
				}

				.statusText {
					font-weight: 400;
					font-size: 26rpx;
					color: #FA2E1B;
					width: 15%;
					text-align: right;
					margin-bottom: 24rpx;
				}

				.statusText1 {
					font-weight: 400;
					font-size: 26rpx;
					color: #999999;
					width: 15%;
					text-align: right;
					margin-bottom: 24rpx;
				}

				.imgShowBox {
					width: 70%;
					overflow: hidden;
				}

				.label {
					display: flex;
					justify-content: flex-start;
					align-items: center;
					width: 80%;
					height: 100%;
					margin-bottom: 24rpx;

					.img {
						width: 26rpx;
						height: 26rpx;
					}

					.imgs {
						width: 12rpx;
						height: 18rpx;
					}

					.imgBox {
						width: 107rpx;
						height: 54rpx;
					}

					text {
						margin-left: 8rpx;
						margin-right: 10rpx;
						display: flex;
						font-family: Source Han Sans CN, Source Han Sans CN;
						font-weight: 500;
						font-size: 28rpx;
						color: #333333;
						line-height: 30rpx;
						text-align: left;
						font-style: normal;
						text-transform: none;
					}
				}

				.tips {
					width: calc(100% - 36rpx);
					margin-top: 20rpx;
					height: 66rpx;
					border-radius: 6rpx 6rpx 6rpx 6rpx;
					display: flex;
					align-items: center;
					padding-left: 18rpx;
					padding-right: 18rpx;
					font-family: PingFang SC, PingFang SC;

					text-align: left;
					font-style: normal;
					text-transform: none;

					.name {
						font-weight: 500;
						font-size: 24rpx;
						color: #333333;
						margin-left: 10rpx;
					}

					.tishi {
						font-weight: 400;
						font-size: 24rpx;
						color: #666666;
						margin-left: 12rpx;
						margin-right: 6rpx;
					}

					.value {
						font-weight: 500;
						font-size: 24rpx;
						color: #FA2E1B;
					}
				}

				.type1 {
					background: #F2F5F7;
				}



				.main {
					.title {
						font-weight: 400;
						font-size: 28rpx;
						color: #333333;
						margin-left: 18rpx;
						overflow: hidden;
						width: 330rpx;
						text-overflow: ellipsis;
						text-transform: none;
						display: -webkit-box;
						-webkit-line-clamp: 2;
						-webkit-box-orient: vertical;
						overflow: hidden;
					}

					.intro {
						font-weight: 400;
						font-size: 24rpx;
						color: #999999;
						margin-left: 18rpx;
						margin-top: 10rpx;
					}

					.img {
						width: 150rpx;
						height: 150rpx;
						border-radius: 10rpx;
					}

					.right {
						width: calc(100% - 342rpx - 170rpx);
						text-align: right;

						.intros {
							text-align: right;
							font-weight: 400;
							font-size: 24rpx;
							color: #999999;
							margin-top: 10rpx;
						}

						.unit {
							font-weight: 500;
							font-size: 22rpx;
							color: #333333;
						}

						.price {
							text-align: right;
							font-weight: 500;
							font-size: 30rpx;
							color: #333333;
						}
					}

				}

				.btn {
					display: flex;
					align-items: center;
					justify-content: flex-end;
					padding: 30rpx 0 0rpx;

					view {
						width: 160rpx;
						height: 66rpx;
						font-family: PingFang SC, PingFang SC;
						font-weight: 400;
						font-size: 24rpx;
						color: #333333;
						line-height: 66rpx;
						text-align: center;
						font-style: normal;
						text-transform: none;
						background: #FDFDFD;
						border-radius: 8rpx;
						border: 1rpx solid #D2D2D2;
						margin-left: 20rpx;

						&:first-child {
							margin-left: 0;
						}
					}

					.type2 {
						color: #FA2E1B;
						border: 1rpx solid #FA2E1B;
					}
				}
			}
		}


		.load-more-box {
			text-align: center;
			width: 100%;
			padding-top: 20rpx;
			padding-bottom: constant(safe-area-inset-bottom);
			padding-bottom: env(safe-area-inset-bottom);
			color: #7A7A7A;
		}

	}
</style>